import 'package:cave_flutter/network/whl_api.dart';
import 'package:cave_flutter/pages/whl_chat/whl_chat_room/chat_setting/chat_set_group_nickname/chat_set_group_nickname_view.dart';
import 'package:cave_flutter/pages/whl_chat/whl_chat_room/chat_setting/complaint/complaint_view.dart';
import 'package:cave_flutter/utils/whl_toast_utils.dart';
import 'package:cave_flutter/widgets/whl_bottom_action_sheet.dart';
import 'package:get/get.dart';
import 'package:nim_core/nim_core.dart';

import '../../../../model/user_model.dart';
import '../../../../routes/whl_app_pages.dart';
import '../whl_chat_room_logic.dart';

class ChatSettingLogic extends GetxController {
  List<String> optionsList = ['聊天', '好友申请', '社区帖子', '头像', '昵称', 'Cave群组/帖子', '心动电台'];

  String toAccountId = '';
  NIMSessionType sessionType = NIMSessionType.p2p;

  bool isBlack = false;
  bool isMute = false;
  bool isTop = false;
  bool isShowSwitch = false;
  UserModel? userModel;
  var centerTitle = "";
  List<NIMUser>? members;
  String groupNickname = '';

  @override
  void onInit() {
    super.onInit();

    var a = Get.arguments;
    if (a != null) {
      print('【cave】arguments: $a');
      toAccountId = a['toAccountId'];
      sessionType = a['sessionType'];
      userModel = a['userModel'];
      isBlack = userModel?.block == 1;

      switch (sessionType) {
        case NIMSessionType.p2p:
          {
            centerTitle = '聊天设置';
            checkStickTopSession();
          }

          break;
        case NIMSessionType.team:
          {
            centerTitle = '群聊设置';
            // getMemberList();
            getUserInfo();
          }
          break;
        default:
          break;
      }
    }
  }

  /// 检测是否是置顶消息
  void checkStickTopSession() async {
    NIMResult<List<NIMStickTopSessionInfo>> result = await NimCore.instance.messageService.queryStickTopSession();
    print('【cave】queryStickTopSession: ${result.data ?? []}');
    for (NIMStickTopSessionInfo sessionInfo in result.data ?? []) {
      if (sessionInfo.sessionType == sessionType && sessionInfo.sessionId == toAccountId) {
        isTop = true;
        break;
      }
    }
    checkMuteState();
  }

  void changeTopState() {
    isTop = !isTop;
    if (isTop) {
      NimCore.instance.messageService.addStickTopSession(toAccountId, sessionType, 'addStickTopSession');
    } else {
      NimCore.instance.messageService.removeStickTopSession(toAccountId, sessionType, 'removeStickTopSession');
    }
  }

  /// 检测是否消息免打扰
  void checkMuteState() async {
    switch (sessionType) {
      case NIMSessionType.p2p:
        {
          NIMResult<List<String>> result = await NimCore.instance.userService.getMuteList();
          for (String item in result.data ?? []) {
            if (item == toAccountId) {
              isMute = true;
              break;
            }
          }
          isShowSwitch = true;
        }

        break;
      case NIMSessionType.team:
        {
          NIMResult<NIMTeam> result = await NimCore.instance.teamService.queryTeam(toAccountId);
          if (result.data != null) {
            NIMTeam team = result.data!;
            isMute = team.messageNotifyType == NIMTeamMessageNotifyTypeEnum.mute;
          }
          isShowSwitch = true;
        }
        break;
      default:
        break;
    }

    update();
  }

  void changeMuteState() {
    isMute = !isMute;

    switch (sessionType) {
      case NIMSessionType.p2p:
        {
          NimCore.instance.userService.setMute(userId: toAccountId, isMute: isMute);
        }

        break;
      case NIMSessionType.team:
        {
          NimCore.instance.teamService.muteTeam(toAccountId, isMute ? NIMTeamMessageNotifyTypeEnum.mute : NIMTeamMessageNotifyTypeEnum.all);
        }
        break;
      default:
        break;
    }
  }

  void getUserInfo() async {
    // NimCore.instance.userService.
    NIMResult<String?> accountResult = await NimCore.instance.userService.getCurrentAccount();
    NIMResult<NIMTeamMember> result = await NimCore.instance.teamService.queryTeamMember(toAccountId, accountResult.data ?? '');
    groupNickname = result.data?.teamNick ?? '';
    checkStickTopSession();
  }

  /// 获取群聊列表
  void getMemberList() async {
    List<String> ids = [];
    NIMResult<List<NIMTeamMember>> result = await NimCore.instance.teamService.queryMemberList(toAccountId);
    for (NIMTeamMember member in result.data ?? []) {
      ids.add(member.id ?? '');
    }

    if (ids.isNotEmpty) {
      NIMResult<List<NIMUser>> result = await NimCore.instance.userService.fetchUserInfoList(ids);
      members = result.data;
    }

    checkStickTopSession();
  }

  /// 设置群昵称
  void setTeamNickname() {
    Get.to(() => ChatSetGroupNamePage(), arguments: {
      'groupId': toAccountId,
      'groupNickname': groupNickname,
    });
  }

  /// 一键举报
  doClickComplaint() {
    /*
    WhlBottomActionSheet.show(optionsList, callBack: (index) {
      Get.toNamed(Routes.complaintPage, arguments: {'title': optionsList[index]});
    });
    */
    Get.to(() => ComplaintPage(), arguments: {'title': '聊天', 'categoryId': '3'});
  }

  goSearchPage() {
    Get.toNamed(Routes.chatSearchPage, arguments: {"toAccountId": toAccountId});
  }

  deleteLocMessage() {
    WhlBottomActionSheet.show(['清空聊天记录'], callBack: (index) async {
      await NimCore.instance.messageService.clearChattingHistory(toAccountId, sessionType, true);
      MyToast.show("删除成功");
      final chatLogic = Get.find<WhlChatRoomLogic>();
      chatLogic.messageList.clear();
      chatLogic.update();
    });
  }

  deleteLocAndServiceMessage() {
    WhlBottomActionSheet.show(['清空本地及服务器聊天记录'], callBack: (index) async {
      await NimCore.instance.messageService.clearChattingHistory(toAccountId, sessionType, true);
      await NimCore.instance.messageService.clearServerHistory(toAccountId, sessionType, false);
      MyToast.show("删除成功");
      final chatLogic = Get.find<WhlChatRoomLogic>();
      chatLogic.messageList.clear();
      chatLogic.update();
    });
  }

  void changeBlackAction() {
    Map<String, dynamic> params = {"accountId": toAccountId, "status": isBlack ? 1 : 0};
    WhlApi.editBlack.post(params).then((value) {
      if (value.isSuccess()) {
        isBlack = !isBlack;
        if (isBlack) {
          MyToast.show("加入黑名单成功");
        } else {
          MyToast.show("黑名单移除成功");
        }
        update();

        WhlChatRoomLogic logic = Get.find<WhlChatRoomLogic>();
        logic.userModel?.block = isBlack ? 1 : 0;
      }
    });
  }

  Future<void> toSetterRemarkPage() async {
    var a = await Get.toNamed(Routes.setterRemarkPage, arguments: {"userModel": userModel});
    if (a != null) {
      update();
    }
  }
}
